var app = require('express')()
var server = require('http').Server(app)
var io = require('socket.io')(server)
const PORT = 3000
const TYPE_MSG = 0
const TYPE_ENTER = 1
const TYPE_LEAVE = 2
server.listen(3000)
// WARNING: app.listen(80) will NOT work here!

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html')
})

let userCount = 0
io.on('connection', function(socket) {
  userCount++
  socket.userName = '用户' + userCount

  // 给所有用户广播消息
  io.emit('server', {
    type: TYPE_ENTER,
    msg: `${socket.userName}进入了聊天室`,
    date: new Date().toLocaleTimeString()
  })

  socket.on('disconnect', data => {
    userCount--
    io.emit('server', {
      type: TYPE_LEAVE,
      msg: `${socket.userName}离开了聊天室`,
      date: new Date().toLocaleTimeString()
    })
  })

  socket.on('msg', msg => {
    io.emit('server', {
      type: TYPE_LEAVE,
      msg: msg,
      date: new Date().toLocaleTimeString()
    })
  })
})
